using System.Collections.Generic;
using System.Data.Linq.SqlClient;
using System.Linq;
using Webbness.Mvc.Models;

namespace Webbness.Mvc.SubSonic
{
    public class RoleRepository<TRole, TJoin, TUser> : SimpleTypedRepository<TRole>
        where TRole : SecurityRole<TRole, TJoin, TUser>, new()
        where TUser : SecurityUser<TUser, TJoin, TRole>, new()
        where TJoin : SecurityUserInRole<TRole, TJoin, TUser>, new()
    {
        public TUser GetUserByUserName(string username)
        {
            return Repository.Repo.Single<TUser>(u => u.UserName == username);
        }

        public TRole GetRoleByName(string name)
        {
            return Repository.Repo.Single<TRole>(r => r.RoleName.ToLower() == name.ToLower());
        }

        public void Save()
        {
            
        }

        public int Add(string name)
        {
            return (int)Add( new TRole {RoleName = name, Description = name});
            
        }

        public int Delete(TRole role)
        {
            return Repository.Repo.Delete<TRole>(role.Id);
        }

        public void AddUserToRole(string u, string r)
        {
            TUser user = GetUserByUserName(u);
            if (user == null)
                return;
            TRole role = GetRoleByName(r);
            if (role == null)
                return;
            var uir = new TJoin {UserID = user.Id, RoleID = role.Id};
            Repository.Repo.Add(uir);
        }

        public int RemoveUserFromRole(string u, string r)
        {
            TUser user = GetUserByUserName(u);
            if (user == null)
                return 0;
            TRole role = GetRoleByName(r);
            if (role == null)
                return 0;

            return Repository.Repo.DeleteMany<TJoin>(uir => uir.RoleID == role.Id && uir.UserID == user.Id);
        }

        public IEnumerable<TUser> FindUsersInRole(string roleName, string usernameToMatch)
        {
            TRole role = GetRoleByName(roleName);
            var i = role.Users.AsQueryable();
            var x = from u in i where SqlMethods.Like(u.UserName, usernameToMatch) select u;
            return x.ToArray();
        }

        public List<TRole> FindAllRoles()
        {
            return Repository.Repo.All<TRole>().ToList();
        }
    }
}